<script setup>
import { Modal } from 'ant-design-vue'
import { ColumnHeightOutlined, DeleteOutlined, DoubleRightOutlined, DownOutlined, EditOutlined, KeyOutlined, LockOutlined, PlusOutlined, ReloadOutlined, SearchOutlined, SettingOutlined, UndoOutlined, UnlockOutlined, UpOutlined } from '@ant-design/icons-vue'
import moment from 'moment'
import { batchWriteOff, getAmountList, getWriteoffList, payBatch, payBatchStatistics } from '~@/api/writeoff/index'

defineOptions({
  name: 'Writeoff',
})
const userTitle = shallowRef('')
const writeOffOpen = ref(false)
const allocateOpen = ref(false)
const allocateLoading = ref(false)
const confirmLoading = ref(false) // 确认加载中
// 批次状态
const statusOptions = shallowRef([
  {
    configKey: 1,
    configValue: '等待打款',
  },
  {
    configKey: 2,
    configValue: '打款失败',
  },
  {
    configKey: 3,
    configValue: '打款成功',
  },
  {
    configKey: 4,
    configValue: '核销失败',
  },
  {
    configKey: 5,
    configValue: '核销处理中',
  },
  {
    configKey: 6,
    configValue: '核销成功',
  },

])
// 多个批次数组
const batchArray = shallowRef([])
// 多个批次数组
const payArray = shallowRef([])
const rules = computed(() => {
  return {
    userName: [
      { required: true, message: '请输入登录名', trigger: 'change' },
    ],
    realName: [
      { required: true, message: '请输入用户名称', trigger: 'change' },
    ],

  }
})
const formState = reactive({
  userId: null,
  userName: '',
  realName: '',
  sex: null,
  phone: '',
  email: '',
  status: 'ACTIVE',
})
const statisticsInfo = reactive({
  userName: '',
  realName: '',
})
// 批次详情
const batchInfo = reactive({
  batchNo: '',
})

const message = useMessage()
const selectedRowKeys = shallowRef([])
const selectedWriteoffKeys = shallowRef([])
const roleData = shallowRef([])
const columns = shallowRef([
  {
    title: '批次日期',
    dataIndex: 'accountDate',
    width: 130,
  },
  {
    title: '批次号',
    dataIndex: 'batchNo',
    width: 280,
  },
  {
    title: '中信侧来账流水号',
    dataIndex: 'citicSerialNo',
    width: 280,
    customRender: ({ text }) => {
      if (text) {
        return text
      }
      else {
        return '--'
      }
    },
  },
  {
    title: '银行核销单号',
    dataIndex: 'bankWriteOffNo',
    width: 280,
    customRender: ({ text }) => {
      if (text) {
        return text
      }
      else {
        return '--'
      }
    },
  },
  {
    title: '批次总金额',
    dataIndex: 'defrayFee',
    width: 120,
  },
  {
    title: '聚富通服务费',
    dataIndex: 'jftServeFee',
    width: 120,
  },
  {
    title: '转账手续费',
    dataIndex: 'transServeFee',
    width: 120,
  },

  {
    title: '批次状态',
    dataIndex: 'statusValue',
    align: 'center',
    width: 150,

  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 200,
    customRender: ({ text }) => {
      if (text) {
        return text
      }
      else {
        return '--'
      }
    },

  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'left',
    fixed: 'right',
    width: 150,

  },
])
const allocateColumns = shallowRef([
  {
    title: '中信来账流水号',
    dataIndex: 'citicSerialNo',
    width: 280,
  },
  {
    title: '付款账户名称',
    dataIndex: 'payAccName',
    ellipsis: true,
  },
  {
    title: '付款账号',
    dataIndex: 'payAccNo',
  },
  {
    title: '来账金额',
    dataIndex: 'transAmount',

  },
  {
    title: '付款附言',
    dataIndex: 'summary',
    width: 150,
    ellipsis: true,

  },
  {
    title: '来账时间',
    dataIndex: 'transTime',
    width: 160,
  },

])
const loading = shallowRef(false)
const amountLoading = shallowRef(false)
const totalNum = shallowRef(0)
const pagination = reactive({
  pageSize: 12,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef([])
const formModel = reactive({
  batchDate: void 0,
  status: void 0,
  batchNo: void 0,
  citicSerialNo: void 0,
  bankWriteOffNo: void 0,
})
const amountModel = reactive({
  transTime: void 0,
})
const tableSize = ref(['large'])
const open = ref(false)
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})
onMounted(() => {
  init()
  // getType();
  // getChannel();
})
// 查询批次列表
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const startTime = formModel.batchDate?.[0]?.format('YYYY-MM-DD')
    const endTime = formModel.batchDate?.[1]?.format('YYYY-MM-DD')
    const { data } = await getWriteoffList({
      param: { ...formModel, startTime, endTime },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })

    dataSource.value = data.data ?? []
    totalNum.value = data.pageInfo.total
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}

// 搜索
async function onSearch() {
  pagination.current = 1
  await init()
}
// 搜索中信动账记录
async function searchOff() {
  getCurrentWrite(amountModel.transTime)
}
// 重置
async function onReset() {
  formModel.batchDate = void 0
  formModel.batchNo = void 0
  formModel.status = void 0
  formModel.citicSerialNo = void 0
  formModel.bankWriteOffNo = void 0
  await init()
}
/**
 * 批次状态
 *
 */
function handleStatus(status) {
  switch (status) {
    case 1:
      return '等待打款'
    case 2:
      return '打款失败'
    case 3:
      return '打款成功'
    case 4:
      return '核销失败'
    case 5:
      return '核销处理中'
    default:
      return '核销成功'
  }
}

// 确认核销
async function handleConfirm() {
  if (selectedWriteoffKeys.value.length <= 0) {
    message.warning('请至少选择一项')
    return false
  }
  confirmLoading.value = true
  try {
    const { data } = await batchWriteOff({ batchNos: batchArray.value, citicSerialNos: selectedWriteoffKeys.value })

    message.success('操作成功')
    // 清除数组
    selectedWriteoffKeys.value = []
    batchArray.value = []
    selectedRowKeys.value = []
    init()
    writeOffOpen.value = false
    confirmLoading.value = false
  }
  catch (error) {
    confirmLoading.value = false
  }
  finally {
    confirmLoading.value = false
  }
}

// 取消核销操作
function handleCancel() {
  writeOffOpen.value = false
  selectedRowKeys.value = []
}
function onSelectChange(value) {
  console.log('selectedRowKeys changed: ', value)
  selectedRowKeys.value = value
}
// 核销选中项改变
function onBatchChange(value) {
  console.log(666, value)
  selectedWriteoffKeys.value = value
}
// 打开核销弹窗
function addWriteoffModal(record) {
  selectedWriteoffKeys.value = []
  batchArray.value = []
  // 批量核销
  if (record === 'all') {
    if (selectedRowKeys.value.length <= 0) {
      message.warning('请至少选择一个批次')
      return false
    }
    batchArray.value = selectedRowKeys.value
    const today = moment().format('YYYY-MM-DD')
    amountModel.transTime = today
    getCurrentWrite(amountModel.transTime)
  }
  else {
    amountModel.transTime = record.accountDate
    batchInfo.batchNo = record.batchNo
    batchArray.value.push(batchInfo.batchNo)
    getCurrentWrite(record.accountDate)
  }
  writeOffOpen.value = true
}
// 批量打款
function payAll(record) {
  payArray.value = []
  if (record.batchNo) {
    const batchInfo = record.batchNo
    payArray.value.push(batchInfo)
    getStatistics(payArray)
  }
  else {
    if (selectedRowKeys.value.length <= 0) {
      message.warning('请至少选择一个批次')
      return false
    }
    getStatistics()
  }
}
// 获取打款统计确认金额
async function getStatistics(type) {
  try {
    if (type) {
      const { data } = await payBatchStatistics({ batchNos: payArray.value })
      statisticsInfo.value = data
    }
    else {
      const { data } = await payBatchStatistics({ batchNos: selectedRowKeys.value })
      statisticsInfo.value = data
    }

    Modal.confirm({
      title: '确认操作',
      centered: true,
      content: `确认本次打款金额为 ${statisticsInfo.value.transferAmount} , 打款手续费为 ${statisticsInfo.value.transferFee} 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        return new Promise((resolve, reject) => {
          const params = {
            batchNos: type ? payArray.value : selectedRowKeys.value,
          }
          const res = payBatch(params)
            .then((res) => {
              if (res.data.code === 'SUCCESS') {
                setTimeout(() => {
                  resolve()
                  selectedRowKeys.value = []
                  payArray.value = []
                  init()
                  message.success('打款成功')
                }, 500)
              }
              else {
                message.error('打款失败')
                reject() // 保持对话框打开
              }
            })
            .catch(() => {
            // message.error('操作失败')
              reject() // 保持对话框打开
            })
        })
      },
      onCancel() {
        console.log('取消操作')
      },
    })
  }
  catch (e) {
    console.log(e)
  }
  finally {
    amountLoading.value = false
  }
}
// 查询资金账户动账记录
async function getCurrentWrite(record) {
  amountLoading.value = true
  roleData.value = []
  try {
    const { data } = await getAmountList(record)
    amountLoading.value = false
    roleData.value = data ?? []
  }
  catch (e) {
    console.log(e)
    amountLoading.value = false
  }
  finally {
    amountLoading.value = false
  }
}

// 编辑用户
async function handleEdit(record) {
  writeOffOpen.value = true
  formState.userId = record.userId
  formState.userName = record.userName
  formState.realName = record.realName
  formState.sex = record.sex
  formState.phone = record.phone
  formState.status = record.status
  formState.email = record.email
  userTitle.value = '编辑用户'
}

function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
// 分页
function handlePageChange() {

}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
function handleCheckAllChange(e) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}
watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}
function handleCheckChange(value) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}
const expand = ref(false)
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :model="formModel">
        <a-row :gutter="[15, 0]">
          <a-col :span="8">
            <a-form-item name="batchDate" label="批次日期">
              <a-range-picker v-model:value="formModel.batchDate" allow-clear style="width:100%" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="bankWriteOffNo" label="银行核销单号">
              <a-input v-model:value="formModel.bankWriteOffNo" placeholder="精确查询" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="citicSerialNo" label="中信侧来账流水号">
              <a-input v-model:value="formModel.citicSerialNo" placeholder="精确查询" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="batchNo" label="批 次 号">
              <a-input v-model:value="formModel.batchNo" placeholder="精确查询" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="status" label="批   次   状   态">
              <a-select v-model:value="formModel.status" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in statusOptions" :key="item.configKey" :value="item.configKey">
                  {{ item.configValue }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-space flex justify-end w-full>
              <a-button type="primary" @click="onSearch">
                查询
              </a-button>
              <a-button @click="onReset">
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card>
      <a-table
        bordered row-key="batchNo" :row-selection="{
          selectedRowKeys,
          onChange: onSelectChange,
        }" :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'defrayFee'">
            <span>{{ Number(record.defrayFee).toFixed(2) }}</span>
          </template>
          <template v-if="column.dataIndex === 'jftServeFee'">
            <span>{{ Number(record.jftServeFee).toFixed(2) }}</span>
          </template>
          <template v-if="column.dataIndex === 'transServeFee'">
            <span>{{ Number(record.transServeFee).toFixed(2) }}</span>
          </template>

          <template v-else-if="column.dataIndex === 'statusValue'">
            {{ handleStatus(record.statusValue) }}
          </template>
          <template v-else-if="column.dataIndex === 'certNo'">
            {{ handleCertcard(record.certNo) }}
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <div class="action flex">
              <span v-if="record.statusValue === 3 || record.statusValue === 4">
                <a @click="addWriteoffModal(record)">核销</a>
              </span>
              <!-- <span v-if="(record.statusValue === 3 || record.statusValue === 4) && (record.statusValue === 1 || record.statusValue === 2) ">
                <span class="middle-line">|</span>
              </span> -->
              <a v-else-if="record.statusValue === 1 || record.statusValue === 2" @click="payAll(record)">打款</a>
              <span v-else>--</span>
            </div>
          </template>
        </template>
      </a-table>
      <div style="margin: 30px 0; display: flex; justify-content: space-between">
        <div>
          <a-space flex justify-end w-full>
            <a-button type="primary" class="ml-2" ghost @click="addWriteoffModal('all')">
              批量核销
            </a-button>
            <a-button type="primary" class="ml-2" ghost @click="payAll">
              批量打款
            </a-button>
          </a-space>
        </div>
        <a-pagination
          v-model:current="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="totalNum"
          :show-total="total => `总共： ${total}`"
          @change="handlePageChange"
        />
      </div>
    </a-card>
    <!-- 手动核销 -->
    <a-modal v-model:open="writeOffOpen" :confirm-loading="confirmLoading" :mask-closable="false" width="1000px" title="手动核销" :body-style="{ paddingTop: '25px', paddingBottom: '50px' }" ok-text="核销" @ok="handleConfirm" @cancel="handleCancel">
      <a-form :model="amountModel">
        <a-row :gutter="[15, 0]">
          <a-col :span="10">
            <a-form-item name="transTime" label="来账日期">
              <a-date-picker
                v-model:value="amountModel.transTime" class="w-1/1" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-button type="primary" @click="searchOff">
              查询
            </a-button>
          </a-col>
        </a-row>
      </a-form>
      <a-table
        class="mt-3" :pagination="false" row-key="citicSerialNo" :style="{ height: '320px' }" :row-selection="{
          selectedRowKeys: selectedWriteoffKeys,
          onChange: onBatchChange,
        }" bordered :loading="amountLoading" :columns="allocateColumns" :data-source="roleData"
      />
    </a-modal>
  </page-container>
</template>

  <style lang="less" scoped>
    :deep(.ant-btn){
       padding: 4px 8px;
    }
    .line{
      color:#1677ff;
    }
    .userTitle{
      color:gray;
      width: 100%;
      padding:5px 0;
      border-bottom:1px solid #f1eded;
      margin-bottom: 20px;
    }
    .red{
      color:red;
      /* color:#ff4d4f; */
    }
    .card-title{
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      flex: auto;
      color: rgba(0, 0, 0, 0.88);
      font-weight: 600;
      font-size: 16px;
      line-height: 1.5;
    }
  @media screen and (max-width: 1200px) and (min-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      margin-left: -44px;
      .statItem {
        padding: 0 16px;
      }
    }
  }

  @media screen and (max-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      float: none;
      margin-right: 0;
      .statItem {
        padding: 0 16px;
        text-align: left;
        &::after {
          display: none;
        }
      }
    }
  }

  @media screen and (max-width: 768px) {
    .extraContent {
      margin-left: -16px;
    }
    .projectList {
      .projectGrid {
        width: 50%;
      }
    }
  }

  @media screen and (max-width: 576px) {
    .pageHeaderContent {
      display: block;
      .content {
        margin-left: 0;
      }
    }
    .extraContent {
      .statItem {
        float: none;
      }
    }
  }

  @media screen and (max-width: 480px) {
    .projectList {
      .projectGrid {
        width: 100%;
      }
    }
  }
  </style>
